package com.hishop.common;

import com.hishop.util.PropertiesUtil;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.util.Hashing;
import redis.clients.util.Sharded;

import java.util.ArrayList;
import java.util.List;

/**
 * 分布式redis,采用hash一致性算法
 *
 * Created by hejie on 2018/3/13.
 */
public class RedisShardedPool {
    private static ShardedJedisPool pool;
    private static Integer maxTotal = Integer.parseInt(PropertiesUtil.getProperty("redis.max.total"));
    private static Integer maxIdle = Integer.parseInt(PropertiesUtil.getProperty("redis.max.idle"));//最大空闲状态
    private static Integer minIdle = Integer.parseInt(PropertiesUtil.getProperty("redis.min.idle"));//最小空闲状态
    private static Boolean testOnBorrow = Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.borrow"));//true得到的jedis实例可用
    private static Boolean testOnReturn = Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.return"));//true返回的jedis实例可用
    private static String ip= PropertiesUtil.getProperty("redis.ip");
    private static Integer port= Integer.parseInt(PropertiesUtil.getProperty("redis.port"));
    private static String password= PropertiesUtil.getProperty("redis.password");
    private static String ip2= PropertiesUtil.getProperty("redis2.ip");
    private static Integer port2= Integer.parseInt(PropertiesUtil.getProperty("redis2.port"));
    private static String password2= PropertiesUtil.getProperty("redis2.password");

    static{
        JedisPoolConfig config=new JedisPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);
        config.setTestOnBorrow(testOnBorrow);
        config.setTestOnReturn(testOnReturn);
        config.setBlockWhenExhausted(true); //连接耗尽时是否阻塞，false会抛异常，true阻塞直到超时
        JedisShardInfo info1 = new JedisShardInfo(ip,port,1000*2);
        info1.setPassword(password); //如果有密码，请设置密码，否则启动会报错！！！
        JedisShardInfo info2 = new JedisShardInfo(ip2,port2,1000*2);
        List<JedisShardInfo> jedisShardInfos = new ArrayList<JedisShardInfo>(2);
        jedisShardInfos.add(info1);
        jedisShardInfos.add(info2);
        pool =new ShardedJedisPool(config,jedisShardInfos, Hashing.MURMUR_HASH, Sharded.DEFAULT_KEY_TAG_PATTERN);
        //分片策略：MURMUR_HASH对应hash一致性算法
    }

    public static ShardedJedis getJedis(){
        return pool.getResource();
    }

    public static void returnResource(ShardedJedis jedis){
        pool.returnResource(jedis);
    }

    public static void returnBrokenResource(ShardedJedis jedis){
        pool.returnBrokenResource(jedis);
    }

    public static void main(String[] args) {
        ShardedJedis jedis=pool.getResource();
        for (int i=0;i<10;i++){
            jedis.set("key_"+i,"value_"+i);
        }
        returnResource(jedis);
      //  pool.destroy();//临时调用，销毁连接池

    }
}
